<template>
  <div>
    <Breadcrumb :style="{margin: '16px 0'}">
      <BreadcrumbItem>首页</BreadcrumbItem>
      <BreadcrumbItem>学校管理</BreadcrumbItem>
      <BreadcrumbItem>学校详情</BreadcrumbItem>
    </Breadcrumb>
    <Card>
      <div style="min-height: 600px">
        <Row>
          <Col span="14" offset="5">
            <List>
              <ListItem>
                <h4>学校名字：</h4>
                <p>{{schoolData.name}}</p>
              </ListItem>
              <ListItem>
                <h4>所在区域：</h4>
                <p>{{schoolData.areaName}}</p>
              </ListItem>
              <ListItem>
                <h4>联系人姓名：</h4>
                <p>{{schoolData.contactName}}</p>
              </ListItem>
              <ListItem>
                <h4>联系方式：</h4>
                <p>{{schoolData.contact}}</p>
              </ListItem>
              <ListItem>
                <h4>是否试用：</h4>
                <Tag
                  type="dot"
                  :color="schoolData.isTrial == 1 ? 'error' : 'primary'"
                >{{schoolData.isTrial == 1 ? '是' : '否'}}</Tag>
              </ListItem>
              <ListItem>
                <Table stripe :columns="columns" :data="schoolData.teacherList"></Table>
              </ListItem>
              <ListItem>
                <h4>已成功申请激活码数量：</h4>
                <div class="cdkeys-cont">
                  <p>{{schoolData.cdkeyCount}}个</p>
                </div>
              </ListItem>
              <ListItem v-if="(schoolData.status == 1 || schoolData.status == -1)">
                <h4>激活码详情：</h4>
                <div class="cdkeys-cont">
                  <p v-for="cdkey in schoolData.cdkeys" v-bind:key="cdkey.id">{{cdkey.cdkey}}</p>
                </div>
              </ListItem>
              <ListItem>
                <h4>申请人：</h4>
                <p>{{schoolData.operaName}}</p>
              </ListItem>
              <ListItem>
                <h4>申请时间：</h4>
                <p>{{schoolData.createTime | formatDate}}</p>
              </ListItem>
              <ListItem>
                <h4>审核状态：</h4>
                <Tag
                  type="dot"
                  :color="(schoolData.status == 1 || schoolData.status == -1) ? 'success' : (schoolData.status == 2 || schoolData.status == 4) ? 'error' : (schoolData.status == 3 || schoolData.status == 5) ? 'warning' : ''"
                >{{(schoolData.status == 1 || schoolData.status == -1) ? '已通过' : schoolData.status == 2 ? '删除' : (schoolData.status == 3 || schoolData.status == 5) ? '待审核' : schoolData.status == 4 ? '已驳回' : '其他'}}</Tag>
                <span v-if="(schoolData.status == 1 || schoolData.status == -1)">{{schoolData.verifyTime | formatDate}}</span>
              </ListItem>
              <ListItem v-if="schoolData.status == 4">
                <h4>原因：</h4>
                <p>{{schoolData.remark || '无'}}</p>
              </ListItem>
              <ListItem v-if="schoolData.status == 3 || schoolData.status == 5">
                <h4>未审核激活码数量：</h4>
                <p>{{schoolData.noVerifyCdkeyCount}}</p>
              </ListItem>
            </List>
          </Col>
        </Row>
        <div v-if="schoolData.status == 3 || schoolData.status == 5 || schoolData.status == 1">
          <Divider>{{adminAuth ? '管理员审核' : '运营人员操作'}}</Divider>
          <Row>
            <Col
              span="14"
              offset="5"
              v-if="adminAuth && (schoolData.status == 3 || schoolData.status == 5)"
            >
              <Button type="success" size="large" @click="handleVerify(1)">通过</Button>
              <Button type="error" size="large" @click="modalBohui = true">驳回</Button>
            </Col>
            <!-- <Col span="14" offset="5" v-if="!adminAuth && (schoolData.status == 3 || schoolData.status == 5)">
            <Button type="primary" size="large" @click="handleVerify(4)">撤销申请</Button>-->
            <!-- <Button type="primary" size="large" @click="handleVerify(4)" v-if="schoolData.status == 4">再次申请</Button> -->
            <!-- </Col> -->
            <Col span="14" offset="5" v-if="!adminAuth && (schoolData.status == 1 || schoolData.status == -1)">
              <Button type="success" size="large" @click="modalAddUsers = true">添加账号</Button>
              <Button type="primary" size="large" @click="modalAddKey = true">新增激活码</Button>
              {{remark}}
            </Col>
          </Row>
        </div>
      </div>
    </Card>
    <Modal v-model="modalAddKey" width="400">
      <p slot="header" style="text-align:left;font-size: 16px;">
        <span>添加激活码</span>
      </p>
      <div style="text-align:center">
        <Input type="number" size="large" v-model="keysCount" placeholder="请输入要新增的激活码数量" />
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="modalAddKey = false">取消</Button>
        <Button type="primary" size="large" @click="handleAddKeys()">确认</Button>
      </div>
    </Modal>
    <Modal v-model="modalAddUsers" width="570">
      <p slot="header" style="text-align:left;font-size: 16px;">
        <span>添加账号</span>
      </p>
      <div>
        <Form>
          <Row v-for="(item, index) in teacherList" :key="index">
            <Col span="8">
              <FormItem :error="item.error">
                <Input
                  type="text"
                  v-model="item.teacherAccount"
                  placeholder="教师账号"
                  @on-blur="checkAccount(index)"
                />
              </FormItem>
            </Col>
            <Col span="4" offset="1">
              <Select v-model="item.levelId">
                <Option label="人音小学" value="1"></Option>
                <Option label="人音初中" value="2"></Option>
                <Option label="人教小学" value="3"></Option>
                <Option label="人教初中" value="4"></Option>
              </Select>
            </Col>
            <Col span="6" offset="1">
              <Input type="text" v-model="item.teacherNickName" placeholder="教师姓名" />
            </Col>
            <Col span="3" offset="1">
              <Button @click="removeTeacherItem(index)" v-if="index > 0">删除</Button>
            </Col>
          </Row>
        </Form>
        <Button @click="addTeacherItem" long icon="md-add">添加</Button>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="modalAddUsers = false">取消</Button>
        <Button type="primary" size="large" @click="handleAddUsers()">确认</Button>
      </div>
    </Modal>
    <Modal v-model="modalBohui" width="400">
      <p slot="header" style="text-align:left;font-size: 16px;">
        <span>将此学校标记为不通过？</span>
      </p>
      <div style="text-align:center">
        <Input type="textarea" v-model="bohui" placeholder="请添加'审核不通过'的备注" />
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="modalBohui = false">取消</Button>
        <Button type="primary" size="large" @click="handleVerify(4)">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import qs from "qs";
export default {
  data() {
    return {
      adminAuth: false,
      modalAddKey: false,
      modalAddUsers: false,
      modalBohui: false,
      bohui: '',
      keysCount: '',
      schoolData: {},
      teacherList: [
        {
          levelId: "1",
          teacherAccount: "",
          teacherNickName: "",
          status: false,
          error: ""
        }
      ],
      columns: [
        {
          title: "用户名",
          key: "nickname"
        },
        {
          title: "手机号",
          key: "phone"
        },
        {
          title: "课程等级",
          key: "levelName"
        }
      ],
      remark: ""
    };
  },
  methods: {
    confirmStatus(_self, n) {
      const remark = n == 4 ? _self.bohui : "";
      // console.log(remark)
      _self.$axios
        .post(
          "/bm/opera/school/verifySchool",
          qs.stringify({
            id: _self.$route.query.id,
            schoolId: _self.$route.query.schoolId,
            status: n,
            remark: remark,
            oldStatus: _self.schoolData.status
          })
        )
        .then(res => {
          if (res.data.code == 200) {
            _self.$Message.success({
              content: "学校审核完成"
            });

            _self.$options.methods.getDetailData(_self)
            _self.modalBohui = false

            // _self.schoolData.status = n;
            // if(n == 4) {
            // } else {
            //   _self.schoolData.noVerifyCdkeyCount = 0
            // }
            // _self.schoolData.createTime = new Date().getTime()
          } else {
            _self.$Message.error({
              content: "状态修改失败，请刷新后重试"
            });
          }
        });
    },
    handleVerify(n) {
      if (n == 4) {
        this.$options.methods.confirmStatus(this, n);
        // this.$Modal.confirm({
        //   title: "将此学校标记为不通过？",
        //   render: h => {
        //     return h("div", [
        //       h("Input", {
        //         props: {
        //           type: "textarea",
        //           placeholder: '请添加"审核不通过"的备注'
        //         },
        //         on: {
        //           "on-change": aaa => {
        //             console.log(aaa)
        //             this.remark = aaa;
        //           }
        //         }
        //       })
        //     ]);
        //   },
        //   onOk: () => {
        //     this.$options.methods.confirmStatus(this, n);
        //   },
        //   onCancel: () => {
        //     this.$Message.warning({
        //       content: "用户取消操作"
        //     });
        //   }
        // });
      } else if (n == 1 || n == 2) {
        this.$Modal.confirm({
          title: "改变学校状态",
          content: "您此次操作将改变学校状态，确定吗？",
          onOk: () => {
            this.$options.methods.confirmStatus(this, n);
          },
          onCancel: () => {
            this.$Message.warning({
              content: "用户取消操作"
            });
          }
        });
      }
    },
    handleAddKeys() {
      if (!(this.keysCount == '')) {
        this.$axios.post('/bm/opera/school/addNewKey', qs.stringify({
          schoolId: this.schoolData.id,
          cdkeyCount: this.keysCount
        })).then(res => {
          if (res.data.code == 200) {
            this.$Message.success('新激活码申请成功！')
            this.modalAddKey = false

            // this.$options.methods.getDetailData(this)
            this.$router.push('/school')
          } else {
            this.$Message.error(res.data.description)
          }
        }).catch(err => {
          this.$Message.error('网络错误，新激活码申请失败！')
        })
      } else {
        this.$Message.error('激活码数量为空，你添加个啥')
      }
    },
    handleAddUsers() {
      let isContinue = false;
      let teacherlist = '';
      this.teacherList.map((item, index) => {
        if(item.error !== '') {
          isContinue = false
          return false;
        } else {
          isContinue = true
        }
        if (item.teacherAccount !== '' && item.teacherNickName !== '') {
          teacherlist += ',' + item.levelId + '-' + item.teacherAccount + '-' + item.teacherNickName
        }
      })
      try {
        teacherlist = teacherlist.substr(1, teacherlist.length)
      } catch(err) {}

      if(isContinue) {
        this.$axios.post('/bm/opera/school/batchInsertUser', qs.stringify({
          schoolId: this.schoolData.id,
          schoolName: this.schoolData.name,
          userList: teacherlist
        })).then(res => {
          if (res.data.code == 200) {
            this.$Message.success('新账户添加成功！')
            // this.schoolData.teacherList = this.schoolData.teacherList.cancat(this.teacherList)
            this.modalAddUsers = false
            this.$options.methods.getDetailData(this)
          } else {
            this.$Message.error(res.data.description)
          }
        })
      }
    },
    addTeacherItem() {
      this.teacherList.push({
        levelId: "1",
        teacherAccount: "",
        teacherNickName: "",
        status: false,
        error: ""
      });
    },
    removeTeacherItem(n) {
      this.teacherList.splice(n, 1);
    },
    checkAccount(index) {
      console.log(this.teacherList[index].teacherAccount)
      if (this.teacherList[index].teacherAccount === "") {
        this.teacherList[index].error = '不能为空！'
      } else {
        this.$axios
          .post(
            "/bm/opera/school/findUserAccount",
            qs.stringify({ account: this.teacherList[index].teacherAccount })
          )
          .then(res => {
            if (res.data.code == 200) {
              this.teacherList[index].error = ''
            } else {
              this.teacherList[index].error = '账号被占用！'
            }
          })
          .catch(err => {
            this.teacherList[index].error = ''
          });
      }
    },
    getDetailData(_self) {
      const url = "/bm/opera/school/findOperaSchoolInfo?schoolId=" + _self.$route.query.schoolId + '&id=' + _self.$route.query.id;
      _self.$axios.get(url).then(res => {
        if (res.data.code == 200) {
          _self.schoolData = res.data.detail;
        }
      });
    }
  },
  mounted: function() {
    this.adminAuth = localStorage.getItem("userLevel") == 1;
    // console.log(this.$route.query)
    // const url =
    //   "/bm/opera/school/findOperaSchoolInfo?schoolId=" + this.$route.query.schoolId + '&id=' + this.$route.query.id;
    // this.$axios.get(url).then(res => {
    //   if (res.data.code == 200) {
    //     this.schoolData = res.data.detail;
    //   }
    // });
    this.$options.methods.getDetailData(this)
  },
  filters: {
    formatDate(time) {
      const newDate = new Date(time);

      return (
        newDate.getFullYear() +
        "-" +
        (newDate.getMonth() + 1) +
        "-" +
        newDate.getDate() +
        " " +
        newDate.getHours() +
        ":" +
        newDate.getMinutes()
      );
    },
    formatCdkey(cdkey) {
      let count = 0
      try{
        count = cdkey.length
      } catch{}

      return count
    }
  }
};
</script>

<style lang="less" scoped>
.cdkeys-cont {
  p {
    display: block;
    margin: 5px 10px;
  }
}

h4 {
  white-space: nowrap;
}
</style>
